package ink.xiaobaibai.controller;

import ink.xiaobaibai.common.TimedTask;
import ink.xiaobaibai.entity.MonthlyTimedTask;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.IMonthlyTimedTaskService;
import ink.xiaobaibai.service.monthly.IDelayTimedTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-07-27
 **/

@Api(tags = "前端请忽略此接口层")
@RestController
@RequestMapping("/local")
public class LocalController {

    @Autowired
    private IMonthlyTimedTaskService timedTaskService;

    @Autowired
    private IDelayTimedTaskService delayTimedTaskService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 开启定时任务,不直接传,使用redis来传
     */
    @GetMapping("/time-task")
    @ApiOperation("开启或关闭定时任务")
    public ResponseFormat openTimeTask() {
        String value = this.stringRedisTemplate.opsForList().leftPop(TimedTask.redisKey);
        while (value != null) {
            MonthlyTimedTask timedTask = this.timedTaskService.getById(Integer.parseInt(value));
            if (timedTask.getOpen()) {
                // 关掉
                this.delayTimedTaskService.closeTimeTask(timedTask);
            } else {
                // 开启
                this.delayTimedTaskService.openTimeTask(timedTask);
            }
            value = this.stringRedisTemplate.opsForList().leftPop(TimedTask.redisKey);
        }
        return ResponseFormat.success();
    }

}
